<template>
  <div
      v-loading="loading"
      v-empty="nopermission"
      class="rc-cont"
      xs-empty-icon="nopermission"
      xs-empty-text="暂无权限">
    <flexbox
        v-if="!isSeas"
        class="rc-head"
        direction="row-reverse">
      <el-button
          v-if="contractSave"
          class="xr-btn--orange rc-head-item"
          icon="el-icon-plus"
          type="primary"
          @click="createClick">新建合同
      </el-button>
    </flexbox>
    <el-table
        :data="list"
        :height="tableHeight"
        :cell-class-name="cellClassName"
        stripe
        style="width: 100%;border: 1px solid #E6E6E6;"
        @row-click="handleRowClick">
      <el-table-column
          v-for="(item, index) in fieldList"
          :key="index"
          :prop="item.prop"
          :formatter="fieldFormatter"
          :label="item.label"
          show-overflow-tooltip/>
    </el-table>
    <c-r-m-full-screen-detail v-model:visible="showFullDetail"
        :id="contractId"
        crm-type="contract"
        @handle="detailHandle"/>
    <c-r-m-all-create v-if="isCreate"
        :action="createActionInfo"
        crm-type="contract"
        @save-success="createSaveSuccess"
        @close="isCreate=false"/>
  </div>
</template>

<script setup>
import CRMAllCreate from '../SzCrud/CRMAllCreate.vue'
import {crmCustomerQueryContractAPI} from '/src/api/crm/customer.js'
import {crmBusinessQueryContractAPI} from '/src/api/crm/business.js'
import CheckStatusMixin from '/src/mixins/CheckStatusMixin.js'
import {useCheckStatusHook} from '/src/hooks/useCheckStatusHook.js'

import {getPermissionByKey} from '/src/utils/index.js'
import {watch, onMounted} from "vue";
import CRMFullScreenDetail from "/src/components/CRMFullScreenDetail.vue"
import {getCurrentInstance, ref} from "vue"
import {useNumberHook} from "@/hooks/useNumberHook.js";
// 引入消息总线
const cxt = getCurrentInstance() //相当于Vue2中的this
const bus = cxt.appContext.config.globalProperties.$bus

const hookCheckStatusMixin = useCheckStatusHook()
const {separator} = useNumberHook()
defineOptions({
  name: 'RelativeContract', // 相关联系人  可能再很多地方展示 放到客户管理目录下
})

const props = defineProps({
  /** 模块ID */
  id: [String, Number],
  /** 没有值就是全部类型 有值就是当个类型 */
  crmType: {
    type: String,
    default: ''
  },
  /** 是公海 默认是客户 */
  isSeas: {
    type: Boolean,
    default: false
  },
  /** 联系人人下 新建商机 需要联系人里的客户信息  合同下需要客户和商机信息 */
  detail: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const loading = ref(false)
const nopermission = ref(false)
const list = ref([])
const fieldList = ref([])
const tableHeight = ref('400px')
const showFullDetail = ref(false)
const isCreate = ref(false) // 控制新建
const contractId = ref('') // 查看全屏联系人详情的 ID
// 创建的相关信息
const createActionInfo = ref({type: 'relative', crmType: props.crmType, data: {}})

const rootTabs = inject('rootTabs')

const contractSave = computed(() => {
  return !!getPermissionByKey('crm.contract.save')
})

watch(() => props.id, (val) => {
  list.value = []
  getDetail()
})

watch(() => rootTabs.currentName, (val) => {
  if (val === 'RelativeContract') {
    getDetail(false)
  }
})

onMounted(() => {
  getDetail()
})


function getFieldList() {
  fieldList.value.push({
    prop: 'contractName',
    width: '200',
    label: '合同名称'
  })
  fieldList.value.push({prop: 'num', width: '200', label: '合同编号'})
  fieldList.value.push({
    prop: 'customerName',
    width: '200',
    label: '客户名称'
  })
  fieldList.value.push({prop: 'money', width: '200', label: '合同金额'})
  fieldList.value.push({
    prop: 'startTime',
    width: '200',
    label: '开始日期'
  })

  fieldList.value.push({prop: 'endTime', width: '200', label: '结束日期'})
  fieldList.value.push({prop: 'checkStatus', width: '200', label: '状态'})
}

function getDetail(loading = true) {
  loading.value = loading
  const request = {
    customer: crmCustomerQueryContractAPI,
    business: crmBusinessQueryContractAPI
  }[props.crmType]
  const params = {pageType: 0}
  params[props.crmType + 'Id'] = props.id
  request(params)
      .then(res => {
        if (fieldList.value.length == 0) {
          getFieldList()
        }
        nopermission.value = false
        loading.value = false
        list.value = res.data.data.list
      })
      .catch(data => {
        if (data.code == 102) {
          nopermission.value = true
        }
        loading.value = false
      })
}

/**
 * 格式化字段
 */
function fieldFormatter(row, column) {
  // 如果需要格式化
  if (column.property === 'checkStatus') {
    return hookCheckStatusMixin.getStatusName(row.checkStatus)
  } else if (column.property == 'money') {
    return separator(row[column.property] || 0)
  }
  return row[column.property]
}

/**
 * 当某一行被点击时会触发该事件
 */
function handleRowClick(row, column, event) {
  if (column.property == 'contractName') {
    contractId.value = row.contractId
    showFullDetail.value = true
  }
}

/**
 * 通过回调控制class
 */
function cellClassName({row, column, rowIndex, columnIndex}) {
  if (column.property === 'contractName') {
    return 'can-visit--underline'
  } else {
    return ''
  }
}

/**
 * 新建
 */
function createClick() {
  // 客户 和 商机 下新建合同
  if (props.crmType == 'business') {
    createActionInfo.value.data['customer'] = props.detail
    createActionInfo.value.data['business'] = props.detail
  } else if (props.crmType == 'customer') {
    createActionInfo.value.data['customer'] = props.detail
  }
  isCreate.value = true
}

function createSaveSuccess() {
  bus.emit('crm-tab-num-update')
  getDetail()
}

/**
 * 详情操作
 */
function detailHandle(data) {
  if (data.type === 'delete') {
    getDetail()
    nextTick(() => {
      bus.emit('crm-tab-num-update')
    })
  }
}


</script>

<script type="text/javascript">

export default {

  components: {

    // CRMAllCreate
  },
  mixins: [CheckStatusMixin],
  props: {},
  data() {
    return {}
  },
  // inject: ['rootTabs'],
  computed: {},
  watch: {},
  mounted() {

  },
  methods: {}
}
</script>
<style lang="scss" scoped>
@import '../../styles/relativecrm';
</style>
